package com.xdwanj.servlet;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mysql.jdbc.StringUtils;
import com.xdwanj.pojo.*;
import com.xdwanj.service.CommodityService;
import com.xdwanj.service.PetService;
import com.xdwanj.service.ShoppingCartService;
import com.xdwanj.service.UserService;
import com.xdwanj.service.impl.*;
import com.xdwanj.util.*;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/user")
public class UserServlet extends HttpServlet {

    /**
     * 根请求地址
     */
    public static final String REQUEST_MAPPING = "user";

    /**
     * 方法属性名
     */
    public static final String METHOD = "method";

    /**
     * 登陆动作
     */
    public static final String LOGIN = "login";
    /**
     * 注册动作
     */
    public static final String REGISTER = "register";
    /**
     * 登出动作
     */
    public static final String LOGOUT = "logout";
    /**
     * 密码修改检查动作
     */
    public static final String PWD_MODIFY = "pwdModify";
    /**
     * 更新密码动作
     */
    public static final String UPDATE_PWD = "updatePwd";

    /**
     * 添加Pet动作
     */
    public static final String ADD_PET = "addPet";
    /**
     * 删除Pet动作
     */
    public static final String DEL_PET = "delPet";
    /**
     * 修改Pet动作
     */
    public static final String UPDATE_PET = "updatePet";
    /**
     * 查询Pet列表
     */
    public static final String PET_LIST = "petList";
    /**
     * 购物车列表
     */
    public static final String SHOPPING_CART = "shoppingCart";
    /**
     * 删除购物车
     */
    public static final String DEL_SHOPPING_CART = "delShoppingCart";
    /**
     * 订单列表
     */
    public static final String ORDER_LIST = "orderList";
    /**
     * 用户功能区标志位
     */
    public static final String USER_FUN = "userFun";


    /**
     * 用户名参数
     */
    public static final String USERNAME = "username";
    /**
     * 密码参数
     */
    public static final String PASSWORD = "password";

    public static final String OLD_PASSWORD = "oldPassword";
    /**
     * 电话号码参数
     */
    public static final String PHONE_NUM = "phoneNum";
    /**
     * 邮箱参数
     */
    public static final String EMAIL = "email";
    /**
     * 昵称参数
     */
    public static final String NAME = "name";

    /**
     * Pet ID
     */
    public static final String PID = "pid";
    /**
     * Pet名字
     */
    public static final String PET_NAME = "petName";
    /**
     * Pet年龄
     */
    public static final String PET_AGE = "petAge";
    /**
     * Pet状态
     */
    public static final String PET_TYPE = "petType";
    /**
     * Pet雌雄
     */
    public static final String PET_SEX = "petSex";
    /**
     * Pet体重
     */
    public static final String PET_WEIGHT = "petWeight";
    /**
     * Pet状态
     */
    public static final String PET_INFO = "petInfo";
    /**
     * Pet绝育状态
     */
    public static final String PET_STERILIZATION = "petSterilization";
    /**
     * Pet 严重程度
     */
    public static final String PET_LEVEL = "petLevel";
    /**
     * Pet 驱虫日期
     */
    public static final String PET_EXPELLINGPARASITEDATE = "petExpellingParasiteDate";
    /**
     * Pet 疫苗史
     */
    public static final String PET_VAC_HISTORY = "petVacHistory";

    /**
     * 用户主键
     */
    public static final String UID = "uid";

    /**
     * 购物车id
     */
    public static final String SCID = "scid";
    /**
     * 转换为订单
     */
    public static final String CONVERSION = "conversion";

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("进入UserServlet...");
        String method = req.getParameter(METHOD);

        switch (method) {
            case LOGIN:  // 登陆请求
                login(req, resp);
                break;
            case REGISTER:  // 注册请求
                register(req, resp);
                break;
            case LOGOUT:  // 登出请求
                logout(req, resp);
                break;
            case PWD_MODIFY:
                pwdModify(req, resp);
                break;
            case UPDATE_PWD:
                updatePwd(req, resp);
                break;
            case SHOPPING_CART:  // 购物车页面
                findAdvertise(req, resp);
                shoppingCart(req, resp);
                break;
            case PET_LIST:  // 宠物列表
                findAdvertise(req, resp);
                petList(req, resp);
                break;
            case ADD_PET:  // 添加宠物动作
                findAdvertise(req, resp);
                addPet(req, resp);
                break;
            case DEL_PET:  // 删除宠物动作
                findAdvertise(req, resp);
                delPet(req, resp);
                break;
            case DEL_SHOPPING_CART:  // 删除购物车动作
                findAdvertise(req, resp);
                delShoppingCart(req, resp);
                break;
            case CONVERSION:  // 转换为订单动作
                findAdvertise(req, resp);
                conversionShop(req, resp);
                break;
            case ORDER_LIST:
                findAdvertise(req, resp);
                orderList(req, resp);
                break;
            default:
                break;
        }
    }

    /**
     * 更新密码
     *
     * @param req
     * @param resp
     * @throws IOException
     */
    private void updatePwd(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String oldPassword = req.getParameter(OLD_PASSWORD);
        User user = (User) req.getSession().getAttribute(ConstantsStr.USER_SESSION);
        String url = null;

        UserService service = new UserServiceImpl();

        service.updatePassword(user.getId(), oldPassword);

        req.getSession().removeAttribute(ConstantsStr.USER_SESSION);

        url = req.getContextPath() + UrlUtil.getUrl(PageServlet.REQUEST_MAPPING, new String[]{PageServlet.POSITION, PageServlet.USER});
        System.out.println("url = " + url);
        resp.sendRedirect(url);
    }

    /**
     * 修改密码的 Ajax 请求受理
     *
     * @param req
     * @param resp
     * @throws IOException
     */
    private void pwdModify(HttpServletRequest req, HttpServletResponse resp) {
        String oldPassword = req.getParameter(OLD_PASSWORD);
        User user = (User) req.getSession().getAttribute(ConstantsStr.USER_SESSION);
        Map<String, String> map = new HashMap<>();
        ObjectMapper mapper = new ObjectMapper();
        String json = "";
        PrintWriter writer = null;


        if (user == null) {
            map.put(ConstantsStr.STATUS, "sessionError");
        } else if (StringUtils.isNullOrEmpty(oldPassword)) {
            map.put(ConstantsStr.STATUS, "error");
        } else if (user.getPassword().equals(oldPassword)) {
            map.put(ConstantsStr.STATUS, "true");
        } else {
            map.put(ConstantsStr.STATUS, "false");
        }

        try {
            json = mapper.writeValueAsString(map);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        resp.setContentType("content/json");
        try {
            writer = resp.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }

        writer.write(json);
        writer.flush();
        writer.close();

    }

    /**
     * 查询订单列表
     *
     * @param req
     * @param resp
     */
    private void orderList(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String url = null;

        OrderServiceImpl ordersService = new OrderServiceImpl();
        User user = (User) req.getSession().getAttribute(ConstantsStr.USER_SESSION);

        int pageSize = ConstantsVal.PAGE_SIZE;
        int currentPageNo = 1;

        String currentPageNoStr = req.getParameter(ConstantsStr.CURRENT_PAGE_NO);

        if (StringUtils.isStrictlyNumeric(currentPageNoStr) && Integer.parseInt(currentPageNoStr) >= 1) {
            currentPageNo = Integer.parseInt(currentPageNoStr);
        }

        PageBean<Order> orderList = ordersService.findOrderListByUid(user.getId(), pageSize, currentPageNo);

        req.setAttribute(ConstantsStr.ORDER_LIST, orderList);
        req.setAttribute(USER_FUN, UserServlet.ORDER_LIST);

        url = ConstantsRes.USER_PAGE;
        System.out.println("url = " + url);
        req.getRequestDispatcher(url).forward(req, resp);
    }

    /**
     * 右边广告条
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    private void findAdvertise(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String url = null;
        int currentPageNo = 1;
        int pageSize = 3;
        int categoryId = 0;
        String queryName = "";

        CommodityService commodityService = new CommodityServiceImpl();
        // String queryName = req.getParameter(ConstantsStr.QUERY_NAME);

        // if (StringUtils.isNullOrEmpty(queryName)) {
        //     queryName = "";
        // }

        String categoryIdStr = req.getParameter("categoryId");
        if (StringUtils.isStrictlyNumeric(categoryIdStr)) {
            categoryId = Integer.parseInt(categoryIdStr);
        }

        PageBean<Commodity> commodityList = commodityService.findCommodityList(queryName, categoryId, currentPageNo, pageSize);

        req.setAttribute(ConstantsStr.ADVERTISE, commodityList);

    }

    /**
     * 转换为订单
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    private void conversionShop(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String url = null;

        ShoppingCartService shoppingCartService = new ShoppingCartServiceImpl();
        User user = (User) req.getSession().getAttribute(ConstantsStr.USER_SESSION);

        //获取UID
        int scid = 0;

        // 判断SCID是否是严格的数字
        if (StringUtils.isStrictlyNumeric(req.getParameter(SCID))) {
            scid = Integer.parseInt(req.getParameter(SCID));
        }

        boolean conversion = shoppingCartService.conversion(user.getId(), scid);

        if (conversion) {
            req.setAttribute(ConstantsStr.STATUS, "转换成功!");
        } else {
            req.setAttribute(ConstantsStr.STATUS, "转换失败!");
        }

        url = ConstantsRes.USER_PAGE;
        System.out.println("url = " + url);
        req.getRequestDispatcher(url).forward(req, resp);
    }

    /**
     * 删除购物车功能
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    private void delShoppingCart(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String url = null;
        int scid = 0;

        ShoppingCartService shoppingCartService = new ShoppingCartServiceImpl();
        User user = (User) req.getSession().getAttribute(ConstantsStr.USER_SESSION);

        if (StringUtils.isStrictlyNumeric(req.getParameter(SCID))) {
            scid = Integer.parseInt(req.getParameter(SCID));
        }

        boolean delete = shoppingCartService.delete(scid, user.getId());

        if (delete) {
            req.setAttribute(ConstantsStr.STATUS, "删除成功!");
        } else {
            req.setAttribute(ConstantsStr.STATUS, "删除失败!");
        }


        url = UrlUtil.getUrl(PageServlet.REQUEST_MAPPING, new String[]{PageServlet.POSITION, PageServlet.USER, UserServlet.METHOD, UserServlet.SHOPPING_CART});
        System.out.println("url = " + url);
        req.getRequestDispatcher(url).forward(req, resp);
    }

    /**
     * 查询购物车列表
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    private void shoppingCart(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String url = null;

        String currentPageNoStr = req.getParameter(ConstantsStr.CURRENT_PAGE_NO);
        String queryName = req.getParameter(ConstantsStr.QUERY_NAME);
        User user = ((User) req.getSession().getAttribute(ConstantsStr.USER_SESSION));

        int pageSize = ConstantsVal.PAGE_SIZE;
        int currentPageNo = 1;

        if (StringUtils.isNullOrEmpty(queryName)) {
            queryName = "";
        }

        if (StringUtils.isStrictlyNumeric(currentPageNoStr) && Integer.parseInt(currentPageNoStr) >= 1) {
            currentPageNo = Integer.parseInt(currentPageNoStr);
        }

        ShoppingCartService userService = new ShoppingCartServiceImpl();

        PageBean<ShoppingCart> shoppingCartList = userService.findShoppingCartList(queryName, user.getId(), currentPageNo, pageSize);

        req.setAttribute(ConstantsStr.SHOPPING_CART_LIST, shoppingCartList);
        req.setAttribute(USER_FUN, UserServlet.SHOPPING_CART);

        url = ConstantsRes.USER_PAGE;
        System.out.println("url = " + url);
        req.getRequestDispatcher(url).forward(req, resp);
    }


    /**
     * 删除pet集合
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    private void delPet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String url = null;
        int pid = 0;

        User user = (User) req.getSession().getAttribute(ConstantsStr.USER_SESSION);

        PetService petService = new PetServiceImpl();

        if (StringUtils.isStrictlyNumeric(req.getParameter(PID))) {
            pid = Integer.parseInt(req.getParameter(PID));
        }

        boolean flag = petService.delPet(pid);

        if (flag) {
            req.setAttribute(ConstantsStr.STATUS, "删除成功!");
        } else {
            req.setAttribute(ConstantsStr.STATUS, "删除失败!");
        }

        //url = ConstantsRes.USER_PAGE;
        url = UrlUtil.getUrl(PageServlet.REQUEST_MAPPING, new String[]{PageServlet.POSITION, PageServlet.USER, UserServlet.METHOD, UserServlet.PET_LIST});
        System.out.println("url = " + url);
        req.getRequestDispatcher(url).forward(req, resp);
    }

    /**
     * 添加pet集合
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    private void addPet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String url = null;
        PetService petService = new PetServiceImpl();
        User user = (User) req.getSession().getAttribute(ConstantsStr.USER_SESSION);
        boolean flag = false;

        String nameStr = req.getParameter(PET_NAME);
        String ageStr = req.getParameter(PET_AGE);
        String typeStr = req.getParameter(PET_TYPE);
        String weightStr = req.getParameter(PET_WEIGHT);
        String sexStr = req.getParameter(PET_SEX);

        if (StringUtils.isNullOrEmpty(nameStr)
                || !StringUtils.isStrictlyNumeric(ageStr)
                || StringUtils.isNullOrEmpty(typeStr)
                || !StringUtils.isStrictlyNumeric(weightStr)
                || !StringUtils.isStrictlyNumeric(sexStr)) {

            req.setAttribute(ConstantsStr.ERROR, "输入的内容非法！");
            url = ConstantsRes.PET_ADD_PAGE;
            System.out.println("url = " + url);
            req.getRequestDispatcher(url).forward(req, resp);
            return;
        }

        flag = petService.addPet(user.getId(),
                Pet.builder()
                        .name(nameStr)
                        .age(Integer.parseInt(ageStr))
                        .petType(typeStr)
                        .weight(Double.parseDouble(weightStr))
                        .sex(Integer.parseInt(sexStr))
                        .level(1)
                        .info("一切正常")
                        .build());

        if (flag) {
            req.setAttribute(ConstantsStr.STATUS, "添加成功!");
        } else {
            req.setAttribute(ConstantsStr.STATUS, "添加失败!");
            url = ConstantsRes.PET_ADD_PAGE;
            System.out.println("url = " + url);
            req.getRequestDispatcher(url).forward(req, resp);
            return;
        }

        url = UrlUtil.getUrl(PageServlet.REQUEST_MAPPING, new String[]{PageServlet.POSITION, PageServlet.USER, UserServlet.METHOD, UserServlet.PET_LIST});
        System.out.println("url = " + url);
        req.getRequestDispatcher(url).forward(req, resp);
    }

    /**
     * 查询PetList集合
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    private void petList(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String url = null;

        UserService userService = new UserServiceImpl();
        User user = (User) req.getSession().getAttribute(ConstantsStr.USER_SESSION);

        int pageSize = ConstantsVal.PAGE_SIZE;
        int currentPageNo = 1;

        PageBean<Pet> petList = userService.findPetListByUid(user.getId(), pageSize, currentPageNo);

        req.setAttribute(ConstantsStr.PET_LIST, petList);
        req.setAttribute(USER_FUN, ConstantsStr.PET_LIST);

        url = ConstantsRes.USER_PAGE;
        System.out.println("url = " + url);
        req.getRequestDispatcher(url).forward(req, resp);
    }

    /**
     * 登出请求
     *
     * @param req
     * @param resp
     */
    private void logout(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        req.getSession().removeAttribute(ConstantsStr.USER_SESSION);
        String url = null;

        url = req.getContextPath() + UrlUtil.getUrl(PageServlet.REQUEST_MAPPING, new String[]{PageServlet.POSITION, PageServlet.LOGIN});
        System.out.println("url = " + url);
        resp.sendRedirect(url);
    }

    /**
     * 注册请求
     *
     * @param req
     * @param resp
     */
    private void register(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String url = null;
        UserService userService = new UserServiceImpl();

        String name = req.getParameter(NAME);
        String username = req.getParameter(USERNAME);
        String password = req.getParameter(PASSWORD);
        String phoneNum = req.getParameter(PHONE_NUM);
        String email = req.getParameter(EMAIL);

        if (StringUtils.isNullOrEmpty(username) || StringUtils.isNullOrEmpty(password) || StringUtils.isNullOrEmpty(phoneNum)) {
            url = UrlUtil.getUrl(PageServlet.REQUEST_MAPPING, new String[]{PageServlet.POSITION, PageServlet.LOGIN});
            System.out.println("url = " + url);
            req.getRequestDispatcher(url).forward(req, resp);
            return;
        }

        User user = userService.register(
                User.builder()
                        .name(name)
                        .username(username)
                        .password(password)
                        .phoneNum(phoneNum)
                        .email(email)
                        .build());

        req.getSession().setAttribute(ConstantsStr.USER_SESSION, user);

        // 注册完毕去用户页面
        url = req.getContextPath() + UrlUtil.getUrl(PageServlet.REQUEST_MAPPING, new String[]{PageServlet.POSITION, PageServlet.USER});
        System.out.println("url = " + url);
        resp.sendRedirect(url);
    }

    /**
     * 登陆请求
     *
     * @param req
     * @param resp
     */
    private void login(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        String url = null;
        User user = null;

        String username = req.getParameter("username");
        String password = req.getParameter("password");

        UserService userService = new UserServiceImpl();

        user = userService.login(username, password);

        if (user != null) { // 登陆成功
            req.getSession().setAttribute(ConstantsStr.USER_SESSION, user);
            url = req.getContextPath() + UrlUtil.getUrl(PageServlet.REQUEST_MAPPING, new String[]{PageServlet.POSITION, PageServlet.USER});
            System.out.println("url = " + url);
            resp.sendRedirect(url);
        } else { // 登陆失败
            req.setAttribute(ConstantsStr.ERROR, "用户名或密码错误");
            url = req.getContextPath() + UrlUtil.getUrl(PageServlet.REQUEST_MAPPING, new String[]{PageServlet.POSITION, PageServlet.LOGIN});
            System.out.println("url = " + url);
            req.getRequestDispatcher(url).forward(req, resp);
        }

    }


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
